package com.jdrx.sw.sewage.service.common;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.google.common.collect.Lists;
import com.jdrx.platform.commons.rest.exception.BizException;
import com.jdrx.sw.sewage.common.config.PathConfig;
import com.jdrx.sw.sewage.common.util.ExcelFillCellMergeStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

@Service
public class ExcleExportService {
    public static final Logger logger = LoggerFactory.getLogger(ExcleExportService.class);
    @Autowired
    private PathConfig pathConfig;

    public void exportExcleStreamWithFileName(HttpServletResponse response, String fileName) throws BizException {
        // 输出
        OutputStream output = null;
        try {
            FileInputStream ips = new FileInputStream(new File(fileName));
            output = response.getOutputStream();
            response.reset();
            response.setHeader("Content-disposition", "attachment; filename=Statistics.xlsx");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            //读取文件流
            int len = 0;
            byte[] buffer = new byte[1024 * 10];
            while ((len = ips.read(buffer)) != -1) {
                output.write(buffer, 0, len);
            }
            output.flush();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("下载失败");
        } finally {
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 根据报表类型导出excle
     *
     * @param response
     * @param reportVOS
     * @param clazz
     * @throws BizException
     */
    public void generateExcel(HttpServletResponse response, List reportVOS, Class clazz, String sheetName) throws BizException {
        List<Object> result = Lists.newArrayList();
        reportVOS.forEach(reportVO -> {
            Object o = null;
            try {
                o = clazz.newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            BeanUtils.copyProperties(reportVO, o);
            result.add(o);
        });
        String fileName = pathConfig.getDownloadPath() + File.separator + System.currentTimeMillis() + ".xlsx";
        //需要合并的列
        int[] mergeColumeIndex = {0};
        //需要从第一行开始，列头第一行
        int mergeRowIndex = 1;
        EasyExcel//将数据映射到DownloadDTO实体类并响应到浏览器
                .write(fileName, clazz)
                //07的excel版本,节省内存
                .excelType(ExcelTypeEnum.XLSX)
                //是否自动关闭输入流
                .autoCloseStream(Boolean.TRUE)
                .registerWriteHandler(new ExcelFillCellMergeStrategy(mergeRowIndex, mergeColumeIndex))
                .sheet(sheetName).doWrite(result);
        this.exportExcleStreamWithFileName(response, fileName);
    }
}
